<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
    <style>
        /* 添加一些基本的CSS样式来美化界面 */
        body { font-family: Arial, sans-serif; }
        form { width: 300px; margin: auto; }
        label, input, button { display: block; margin-bottom: 10px; }
        input, button { width: 100%; padding: 8px; }
        button { cursor: pointer; background-color: #4CAF50; color: white; border: none; }
        button:hover { background-color: #45a049; }
    </style>
</head>
<body>
<h2>用户注册</h2>
<!-- 表单提交到/api/users/register路径，使用POST方法 -->
<form id="registrationForm" action="/api/users/register" method="post">
    <div>
        <!-- 输入用户名，表单字段名称为"username" -->
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required>
    </div>
    <div>
        <!-- 输入密码，表单字段名称为"password" -->
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
    </div>
    <div>
        <!-- 提交按钮 -->
        <button type="submit">注册</button>
    </div>
</form>
<div id="registrationResult" style="display:none;"></div>

<script>
    document.getElementById('registrationForm').addEventListener('submit', function(event) {
        event.preventDefault();
        var formData = new FormData(this);
        fetch('/api/users/register', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(data => {
                document.getElementById('registrationResult').innerText = data;
                document.getElementById('registrationResult').style.display = 'block';
                if (data === "User registered successfully") {
                    setTimeout(function() {
                        window.location.href = '/userlogin';
                    }, 500);
                } else if (data === "Username already exists") {
                    // 可以添加更多的用户交互，比如高亮显示用户名输入框等
                    alert("用户名已存在，请选择其他用户名。");
                }
            })
            .catch(error => console.error('Error:', error));
    });
</script>
</body>
</html>